'use strict';

const Controller = require('egg').Controller;

class DiaryController extends Controller {
    get user() {
        return this.ctx.session.user;
      }
    async allDiarys() {
    
        const { ctx } = this;
        console.log(this.user)
        let res = {}
        const result = await this.app.mysql.select('Diary', {
            diary_user: this.user
        });
        res.data = result
        res.msg = "获取成功"
        ctx.body = res
    }

    async addDiarys() {
        const { ctx } = this;
        let Msg = ctx.request.body;

        // 接口数据规则
        // const rule = {
        //     diary_title: { type: 'string', required: true },
        //     diary_content: { type: 'string', required: true },
        //     diary_time: { type: 'string', required: false },
        //     diary_attraction: { type: 'string', required: true },
        //     diary_place: { type: 'string', required: false }
        // };

        try {
            // await ctx.validate(rule, Msg);//校验数据
            Msg.diary_user = this.user
            const result = await this.app.mysql.insert('diary', Msg);
            let res = {}
            if (result.affectedRows !== 1) {
                this.ctx.status = 400;
                res.msg = '新建日记失败';
                ctx.body = res;
            }else {
                res.msg = '新建日记成功';
                ctx.body = res;
            }
     
        }
        catch (e) {
            console.log(e);
            ctx.status = 400;
            ctx.body = '请求参数格式不合法'
        }
        
    }
    async deleteDiarys() {
        const { ctx } = this;
        let id = ctx.request.body.diary_id
        let result1 = await this.app.mysql.delete('diary', {
            diary_id: parseInt(id)
        });
        let res = {}
        if (result1.affectedRows != 1) {
            ctx.status = 400;
            res.msg = '删除日记失败'
            ctx.body = res
        }
        else {
            ctx.status = 200;
            res.msg = '删除日记成功'
            ctx.body = res
        }
    }
    async modifyDiarys() {
        const { ctx } = this;
        let id = ctx.request.body.diary_id
        let updateInfo = ctx.request.body.updateInfo
        let result = await this.app.mysql.update('diary', updateInfo, {
            where: {
              diary_id: id
            }
        })
        let res = {}
        if (result.affectedRows != 1) {
            ctx.status = 400;
            res.msg = '更新日记失败'
            ctx.body = res
        }
        else {
            ctx.status = 200;
            res.msg = '更新日记成功'
            ctx.body = res
        }
    }
}
module.exports = DiaryController;
